<template>
  <div>
    <el-card style="margin: 20px 0px">
      <CategorySelect @getCategoryId="getCategoryId" :show="!isShowTable"></CategorySelect>
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="addAttr"
          >添加属性</el-button
        >
        <!-- 表格展示平台属性 -->
        <el-table :data="attrList" style="width: 100%" border>
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150px">
          </el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                type="success"
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                style="margin: 10px 20px 10px 0px"
              >
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="200px">
            <template slot-scope="{ row }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="updateAttr(row)"
                >修改</el-button
              >
              <el-button type="danger" icon="el-icon-delete" size="mini"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性 修改属性的结构 -->
      <div v-show="!isShowTable">
        <el-form ref="form" :inline="true" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrValue"
          :disabled="!attrInfo.attrName"
          >添加属性值</el-button
        >
        <el-button @click="isShowTable = true">取消</el-button>
        <el-table
          style="width: 100%; margin: 20px 0px"
          border
          :data="attrInfo.attrValueList"
        >
          <el-table-column align="center" type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column width="width" prop="prop" label="属性值名称">
            <template slot-scope="{ row, $index }">
              <el-input
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                size="mini"
                :ref="$index"
                v-if="row.flag"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
              ></el-input>
              <span
                v-else
                @click="toEdit(row, $index)"
                style="display: block"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column width="width" prop="prop" label="操作">
            <template slot-scope="{row, $index}">
              <el-popconfirm :title='`确定删除 "${row.valueName}" 吗？`' @onConfirm="deleteAttrValue($index)">
                <el-button type="danger" icon="el-icon-delete" slot="reference">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addOrUpdateAttr" :disabled="attrInfo.attrValueList.length < 1">保存</el-button>
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
// 按需引入lodash中的深拷贝
import cloneDeep from "lodash/cloneDeep";

export default {
  name: "Attr",
  data() {
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
      // 接收平台属性的字段
      attrList: [],
      // table的显示与隐藏
      isShowTable: true,
      // 收集新增属性 | 修改属性使用
      attrInfo: {
        attrName: "",
        attrValueList: [
          // 属性值 多个要用数组
        ],
        categoryId: 0,
        categoryLevel: 3, // 服务器需要区分几级id
      },
    };
  },
  methods: {
    // 自定义事件
    getCategoryId({ categoryId, level }) {
      // console.log(categoryId);
      // 区分三级分类相应的id 给父组件存储
      if (level == 1) {
        this.category1Id = categoryId;
        this.category2Id = "";
        this.category3Id = "";
      } else if (level == 2) {
        this.category2Id = categoryId;
        this.category3Id = "";
      } else {
        this.category3Id = categoryId;
        // 发请求获取平台属性的数据
        this.getAttrList();
      }
    },
    // 获取平台属性数据的方法
    async getAttrList() {
      // 获取一二三级分类的id
      const { category1Id, category2Id, category3Id } = this;
      let result = await this.$API.attr.reqAttrList(
        category1Id,
        category2Id,
        category3Id
      );
      // console.log(result);
      if (result.code == 200) {
        this.attrList = result.data;
      }
    },
    // 添加属性值回调
    addAttrValue() {
      // 向attrValueList的数组里添加元素
      // attrId：相应属性的id valueName：相应属性值的名称
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id,
        valueName: "",
        flag: true,
      });
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus();
      });
    },
    // 添加属性按钮的回调
    addAttr() {
      this.isShowTable = false;
      this.attrInfo = {
        attrName: "",
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3
      };
    },
    // 修改按钮的回调
    updateAttr(row) {
      this.isShowTable = false;
      // 将选中的属性赋值给attrInfo
      // 由于数据结构当中存在对象套数组 数组再套对象 因此需要用深拷贝来解决
      this.attrInfo = cloneDeep(row);
      // 修改属性时 将相应属性值元素添加上flag标记
      this.attrInfo.attrValueList.forEach((item) => {
        // Vue无法探测普通的新增prototype item.flag=false这样书写的属性并非响应式属性(数据变化视图也变化)
        // $set(对象, 添加新的响应式属性, 新的属性的属性值)
        this.$set(item, "flag", false);
      });
    },
    // 失去焦点的事件 隐藏input展示span
    toLook(row) {
      // row：是用户添加的最新的属性值
      if (row.valueName.trim() == "") {
        this.$message("请你输入一个正常的属性值");
        return;
      }
      // 新增属性值不能与原有属性值重复
      let isRepeat = this.attrInfo.attrValueList.some((item) => {
        // 判断时需要把已有数组中新增的这个属性值(数组最后一项)去除
        if (row !== item) {
          return row.valueName == item.valueName;
        }
      });
      if (isRepeat) {
        this.$message("不可输入重复的属性值");
        return;
      }
      row.flag = false;
    },
    // 点击span的回调 input自动获取焦点
    toEdit(row, index) {
      row.flag = true;
      // $nextTick当节点渲染完毕执行一次
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    // 气泡确认框的确定按钮的回调
    deleteAttrValue(index) {
      this.attrInfo.attrValueList.splice(index, 1);
    },
    // 保存按钮的回调 进行添加属性或修改属性值的操作
    async addOrUpdateAttr() {
      // 整理参数 不提交服务器不需要的flag字段
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(item => {
        // 过滤掉属性值不为空的
        if(item.valueName != '') {
          // 删除flag字段
          delete item.flag;
          return true;
        }
      })
      // 发请求
      try {
        let result = await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo);
        // console.log(result);
        this.isShowTable = true;
        this.$message({type: 'success', message: '保存成功'});
        // 保存成功后再次获取平台属性进行展示
        this.getAttrList();
      } catch (error) {
        this.$message('保存失败');
      }
    }
  },
};
</script>

<style></style>
